package com.example.eventbus.events;

import com.google.common.eventbus.AsyncEventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.lang.reflect.ParameterizedType;

/**
 * @author 谢汉冰
 * @Title: MyEventHandlerImpl
 * @Package com.example.eventbus.events.impl
 * @date 2023/10/23 16:08
 * @description:
 */
@SuppressWarnings("all")
public abstract class MyEventHandler<Listener, Command, Result> extends ApplicationObjectSupport {

	@Autowired
	protected AsyncEventBus eventBus;

	protected Class<Listener> listenerClass;
	protected Class<Command> commandClass;
	protected Class<Result> resultClass;

	public MyEventHandler() {
		listenerClass = (Class<Listener>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		commandClass = (Class<Command>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
		resultClass = (Class<Result>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[2];
	}

	/**
	 * 注册总线
	 */
	@PostConstruct
	public void init() {
		eventBus.register(getBean(listenerClass));
	}

	/**
	 * get bean
	 *
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public <T> T getBean(Class<T> clazz) {
		ApplicationContext context = getApplicationContext();
		if (context != null) {
			return context.getBean(clazz);
		}
		return null;
	}


	/**
	 * 注销总线
	 */
	@PreDestroy
	public void destroy() {
		eventBus.register(getBean(listenerClass));
	}

	/**
	 * 发送请求
	 *
	 * @param command
	 */
	public abstract Result send(Command command);
}
